package com.jlz.managers.def;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jlz.beans.def.SiteBean;
import com.jlz.service.IdentifierService;
import com.julewa.db.DB;
import com.julewa.utils.Patterns;

@Service
public class Sites {
	private @Autowired DB db;
	private @Autowired IdentifierService idsrv;
	private Map<Integer, SiteBean> siteIds = null;
	private Map<String, SiteBean> siteNames = null;
	public static final Integer JULEZU = 0;
	public static final Integer MOBILE = 16;
	public static final Integer PHONE  = 32;
	public static final Integer SITES  = 128;
	
	@SuppressWarnings({ "unused", "unchecked" })
	@PostConstruct
	private void loadAll(){
		//
		this.siteIds = Collections.synchronizedMap(new HashMap<Integer, SiteBean>());
		this.siteNames = Collections.synchronizedMap(new HashMap<String, SiteBean>());
		//
		List<SiteBean> ls = db.getList("site.all", null);
		if(ls == null)ls = new ArrayList<SiteBean>();
		if(ls.isEmpty()){
			SiteBean site = db.create(SiteBean.class);
			site.setID(SITES);
			site.setDomain("qq.com");
			//site.setType(type)
			db.insert("site.insert", site);
			ls.add(site);
			return;
		}
		for(SiteBean b:ls){
			siteIds.put(b.getID(), b);
			siteNames.put(b.getDomain(), b);
		}
	}
	
	public SiteBean get(Integer siteId){
		return siteIds.get(siteId);
	}
	
	public SiteBean find(String domain){
		if(StringUtils.isBlank(domain)){
			return siteIds.get(JULEZU);
		}
		//find by domain
		domain = domain.trim().toLowerCase();
		SiteBean b = siteNames.get(domain);
		if(b != null)return b;
		//check if it is a domain
		if(!Patterns.DOMAIN.match(domain)){
			return null;
		}
		//if not find, then create this one
		b  = new SiteBean();
		b.setID((int)idsrv.generate("site"));
		b.setDomain(domain);
		//b.setType(Sites.)
		b.setDescription("尚未处理的域");
		//
		return b;
	}
	
	public Collection<SiteBean> all(){
		return siteIds.values();
	}
	
	public void append(SiteBean b){
		if(b.getID() != null) return;
		b.setID((int)idsrv.generate("site"));
		db.insert("site.insert", b);
		this.siteIds.put(b.getID(), b);
		this.siteNames.put(b.getDomain(), b);
	}
	
	public void remove(SiteBean b){
		if(b.getID() == null) return;
		this.siteIds.remove(b.getID());
		this.siteNames.remove(b.getDomain());
		db.delete("site.delete", b);
	}

}
